<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadFn"
  >
    <!-- 上传后展示的图片 -->
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import { fileUpload } from '@/api'
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  watch: {
    value: {
      handler() {
        this.imageUrl = this.value
      },
      immediate: true
    }
  },
  methods: {
    // 图片上传
    beforeAvatarUpload(file) {
      const fileList = ['image/jpg', 'image/png']
      const isJPG = fileList.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 1

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
      }
      return isJPG && isLt2M
    },
    async uploadFn(obj) {
      console.log(obj)
      const formData = new FormData()
      formData.append('fileName', obj.file)
      console.log(formData)
      const res = await fileUpload(formData)
      console.log(res)
      this.imageUrl = res.data
      this.$emit('input', this.imageUrl)
    }
  }
}
</script>

<style lang="scss" scoped>
// .avatar-uploader {
//   border: 1px dashed #d9d9d9;
//   border-radius: 6px;
//   cursor: pointer;
//   position: relative;
//   overflow: hidden;
//   font-size: 28px;
//   width: 84px;
//   height: 84px;
//   line-height: 84px;
//   text-align: center;
//   color: #bac0cd;
//   background-color: #f3f6fb;
//   &:hover {
//     border: 1px dashed black;
//   }
// }
// .svg-icon {
//   font-size: 25px;
// }
// .el-upload--text {
//   font-size: 28px;
//   color: #8c939d;
//   width: 84px;
//   height: 84px;
//   line-height: 84px;
//   text-align: center;
// }
// .avatar {
//   width: 84px;
//   height: 84px;
//   display: block;
// }
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 84px;
    height: 84px;
    line-height: 84px;
    text-align: center;
  }
  .avatar {
    width: 84px;
    height: 84px;
    display: block;
  }
</style>
